<template>
	<view class="container">
		<!-- 消息首页 -->
		<uni-nav-bar class="ch-nav" :class="{'navborder': navBorder}" height="88rpx" backgroundColor="#fff" fixed="true"
			:padding="false" :border="false">
			<view class="tab-nav flex-r ac jc" @tap="dbClick">
				<text class="tab color-grey" v-for="(item,index) in tabList" :key="index"
					:class="{'active': tabCur == index}" @tap.top="tabChange(index)">{{item.name}}</text>
			</view>
			<template slot="right" v-if="tabCur == 0">
				<image class="right" src="@/public/images/public/dhl_ss.png" mode="aspectFit"
					@tap="$goByName('msgsearch')"></image>
			</template>
		</uni-nav-bar>
		<scroll-view class="scroll-Y" id="scrollView" :scroll-y="true" :scroll-into-view="nextView"
			:scroll-with-animation="true" :refresher-enabled="true" :refresher-triggered="refreshing"
			refresher-default-style="none" refresher-background="rgba(255, 255, 255, 0)" @scrolltolower="reachBottom"
			@refresherrefresh="refresh" @scroll="scroll">
			<view class="body" id="message">
				<keep-alive>
					<view class="message flex-c" v-if="tabCur == 0">
						<EmptyContent v-if="!messageLists[0]" top="260rpx" text="暂无消息" img="qsy_zwxx"
							@refresh="getMsgLists"></EmptyContent>
						<view class="message-list" v-else>
							<uni-swipe-action>
								<template v-for="(msg, index) in messageLists">
									<uni-swipe-action-item class="swipe-item">
										<view class="message-item flex-r" :key="index" :id="'msg-' + index"
											:class="{'isPinned': msg.isPinned, 'unread': msg.unreadCount}"
											:ref="msg.unreadCount ? 'unread' : 'read'" :data-index="index"
											@tap="goChatBox(msg.conversationID)">
											<view class="left flex-r">
												<lazy-image class="avatar bg"
													:src="msg.userProfile.avatar+'?imageView2/1/w/100/h/100/q/50'"
													type="expert" fit="cover"></lazy-image>
												<view class="note" v-if="msg.unreadCount">
													<text>{{msg.unreadCount > 99 ? '···' : msg.unreadCount}}</text>
												</view>
											</view>
											<view class="right flex-r">
												<view class="content flex-c">
													<view class="top flex-r">
														<text class="title">{{msg.userProfile.nick}}</text>
														<text class="time color-grey"
															v-if="msg.lastMessage.lastTime">{{$CHS.dateFormat(msg.lastMessage.lastTime)}}</text>
													</view>
													<view class="info color-grey"
														v-if="msg.lastMessage.type == 'TIMTextElem'">
														<template v-for="(item,index) in parseTextMsg(msg.lastMessage)">
															<span v-if="item.name != 'img'"
																v-html="item.text.replace(/<br>/ig, ' ')"></span>
															<img v-else class="face-message" :src="item.src"
																style="width: 26rpx;height: 26rpx;object-fit: cover;" />
														</template>
													</view>
													<view class="info color-grey"
														v-else-if="msg.lastMessage.type == 'TIMCustomElem'">
														{{msg.lastMessage.payload.extension}}
													</view>
													<view class="info color-grey"
														v-else-if="msg.lastMessage.type == 'TIMFaceElem'">
														{{msg.lastMessage.payload.data}}
													</view>
													<view class="info color-grey" v-else>
														{{msg.lastMessage.messageForShow}}
													</view>
												</view>
											</view>
										</view>
										<template v-slot:right>
											<view class="slot-button flex-r">
												<view class="slot-button-text pinned-msg flex-r ac jc"
													:class="{'grey': msg.isPinned}"
													@tap="pinConversation(msg.conversationID, msg.isPinned)">
													<text
														class="text-regular color-white">{{msg.isPinned ? '取消置顶' : '置顶'}}</text>
												</view>
												<view class="slot-button-text delete-msg flex-r ac jc"
													@tap="delConversation(msg.conversationID)">
													<text class="text-regular color-white">删除</text>
												</view>
											</view>
										</template>
									</uni-swipe-action-item>
								</template>
							</uni-swipe-action>
						</view>
					</view>
				</keep-alive>
				<keep-alive>
					<view class="notice flex-c" v-if="tabCur == 1">
						<EmptyContent v-if="!noticeLists[0]" top="260rpx" text="暂无通知" img="qsy_zwxx"
							@refresh="getNoticeLists"></EmptyContent>
						<view class="notice-list flex-c" v-else>
							<view class="notice-item flex-c" v-for="(notice, index) in noticeLists"
								:class="{'read': notice.isRead}" :key="index" @tap="goNoticeDetail(notice)">
								<view class="notice-head flex-r thinborder">
									<image v-if="notice.title.includes('专家连红')"
										:src="require('@/public/images/message/zjlmtx_' + (notice.isRead ? 'yd' : 'wd') + '.png')"
										mode="aspectFit"></image>
									<image v-else-if="notice.title.includes('补单')"
										:src="require('@/public/images/message/bdtx_' + (notice.isRead ? 'yd' : 'wd') + '.png')"
										mode="aspectFit"></image>
									<image v-else-if="notice.title.includes('回复') || notice.title.includes('留言')"
										:src="require('@/public/images/message/hftx_' + (notice.isRead ? 'yd' : 'wd') + '.png')"
										mode="aspectFit"></image>
									<image v-else-if="notice.title.includes('优享服务')"
										:src="require('@/public/images/message/yxfw_' + (notice.isRead ? 'yd' : 'wd') + '.png')"
										mode="aspectFit"></image>
									<image v-else-if="notice.title.includes('幸运派送')"
										:src="require('@/public/images/message/xyps_' + (notice.isRead ? 'yd' : 'wd') + '.png')"
										mode="aspectFit"></image>
									<image v-else-if="notice.title.includes('活动')"
										:src="require('@/public/images/message/hdtx_' + (notice.isRead ? 'yd' : 'wd') + '.png')"
										mode="aspectFit"></image>
									<image v-else-if="notice.title.includes('温馨') || notice.title.includes('签到')"
										:src="require('@/public/images/message/qdtx_' + (notice.isRead ? 'yd' : 'wd') + '.png')"
										mode="aspectFit"></image>
									<image v-else
										:src="require('@/public/images/message/xxtz_' + (notice.isRead ? 'yd' : 'wd') + '.png')"
										mode="aspectFit"></image>
									<text class="text-bold text-hidden">{{ notice.title || '通知提醒' }}</text>
									<uni-dateformat class="date" :date="notice.sendTime"
										format="yyyy-M-d hh:mm"></uni-dateformat>
								</view>
								<view class="notice-content" v-if="notice.content" v-html="notice.content"></view>
							</view>
						</view>
						<view class="list-end flex-r" v-if="tabData[tabCur].isEnd && noticeLists[0]">
							<view class="list-end-line"></view>
							<text>加载完成，以上消息为近30天内的通知消息</text>
							<view class="list-end-line"></view>
						</view>
						<Popup v-if="showPopup" :show="showPopup" @getShow="getShow" :FriendDetail="FriendDetail" :resources='resources'></Popup>
					</view>				
				</keep-alive>
			</view>
		</scroll-view>
		<AppDown v-if="platform!='ios'"></AppDown>
	</view>
</template>

<script>
	import imMsg from "@/utils/common/message.js";
	import {
		parseText
	} from "./components/tim-emoji/message-facade.js";
	import CONFIG from '@/config'
	const TIM = imMsg.TIM
	const tim = imMsg.tim()
	export default {
		data() {
			return {
				messageLists: [], //消息列表
				noticeLists: [], //通知列表
				nextView: '', //消息列表的id，用于跳转未读消息
				currentIndex: 0, //当前消息位置

				tabList: [ //顶部tab列表信息
					{
						name: '消息'
					}, {
						name: '通知'
					}
				],
				tabCur: 0, //当前tab索引
				tabData: [ //tab数据
					{
						pageNo: 1,
						isEnd: false
					},
					{
						pageNo: 1,
						isEnd: false
					}
				],
				navBorder: false, //顶部导航下边框
				refreshing: false, //刷新状态
				scrollTop: 0, //scrollview滚动高度

				msgScrollTop: 0 ,//消息列表滚动高度
				showPopup:false,//控制好友申请弹窗
				FriendDetail:[],//好友请求数据详情
				resources:null,
			}
		},
		components:{
			Popup: () => import("./components/ch-popup/ch-popup.vue") //弹窗
		},
		computed: {
			user() {
				return this.$store.state.user
			},
			imReady() {
				return this.$store.state.imReady
			}
		},
		watch: {
			imReady(newValue, oldValue) {
				if (newValue) {
					//获取回话列表
					this.getMsgLists()
				}
			},
			tabCur(newValue, oldValue) {
				if (newValue == 1) {
					//更新通知
					this.tabData[this.tabCur].pageNo = 1
					this.getNoticeLists()
				}
			},
			messageLists(newValue) {
				if (newValue[0]) {
					console.log(newValue);
					this.$nextTick(() => {
						uni.createSelectorQuery().select('#msg-0').boundingClientRect(result => {
							this.msgScrollTop = result ? result.top : 0; //更新消息列表距离顶部的距离
						}).exec()
					})
				}
			}
		},
		onTabItemTap() {
			//双击tabbar滚动到未读消息
			if (this.tabClick) { // 500ms 内再次点击
				if (this.tabCur == 0) {
					let msgList = this.$refs.unread; //获取未读消息列表
					if (msgList.length > 0) { //存在未读消息
						if (msgList.length == 1) {
							//只有一个未读时跳转到该消息
							this.currentIndex = 0
							this.nextView = msgList[0].$el.id
							this.$nextTick(() => { //释放nextView
								this.nextView = ''
							})
						} else {
							//计算当前可视区域所在的消息位置
							uni.createSelectorQuery().select('#msg-0').boundingClientRect((result) => {
								let nowIndex = Math.ceil((this.msgScrollTop - result.top) / result.height);
								//触发滚动
								this.messageScroll(nowIndex);
							}).exec()
						}
					} else { //没有未读消息时跳转到列表底部
						let index = this.messageLists.length - 1
						this.nextView = 'msg-' + index
						this.$nextTick(() => { //释放nextView
							this.nextView = ''
						})
					}
				} else {
					//回到通知列表顶部
					this.nextView = 'message'
					this.$nextTick(() => {
						this.nextView = ''
					})
				}
			}
			//记录点击状态
			this.tabClick = true
			setTimeout(() => {
				this.tabClick = false // 500ms 内没有第二次点击，就当作单击
			}, 500)
		},
		onLoad() {
			//会话列表更新监听
			const onConversationListUpdated = (event) => {
				this.messageLists = event.data
			};
			this.messageListUpdated = onConversationListUpdated
			tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.messageListUpdated);
			//已登录更新会话
			if (this.imReady) {
				this.getMsgLists()
			}
		},
		onShow() {
			if (this.scrollTop > 10) {
				this.navBorder = true
			} else {
				this.navBorder = false
			}
			if (this.imReady) { //更新未读消息数
				let totalUnreadCount = tim.getTotalUnreadMessageCount();
				this.$store.commit("UPDATE_UNREADMSG", totalUnreadCount)
			}
		},
		onUnload() {
			if (this.messageListUpdated) { //移除监听
				tim.off(TIM.EVENT.MESSAGE_RECEIVED, this.messageListUpdated);
			}
		},
		methods: {
			//滚动监听
			scroll(e) {
				this.scrollTop = e.detail.scrollTop
				if (e.detail.scrollTop > 10) {
					this.navBorder = true
				} else {
					this.navBorder = false
				}
			},
			//下拉刷新
			refresh() {
				this.refreshing = true
				if (this.tabCur == 0) {
					//更新消息列表
					this.getMsgLists()
				} else {
					//更新通知
					this.tabData[this.tabCur].pageNo = 1
					this.getNoticeLists()
				}
				setTimeout(() => {
					this.refreshing = false
				}, 1000)
			},
			//触底加载更多
			reachBottom() {
				if (this.tabCur == 1) {
					if (!this.tabData[this.tabCur].isEnd) {
						this.getNoticeLists()
					}
				}
			},
			//查询消息列表
			getMsgLists() {
				this.$ShowLoading({
					show: true
				})
				if (this.imReady) {
					imMsg.getMsgList().then((imResponse) => {
						console.log(imResponse.data);
						this.messageLists = imResponse.data.conversationList
					}).catch((imError) => {
						console.log(imError);
					}).finally(() => {
						this.$ShowLoading({
							show: false
						})
					})
				} else {
					imMsg.login().then((imResponse) => {
						console.log(imResponse);
					}).catch((err) => {
						console.log(err);
						this.$ShowToast({
							text: '状态异常，请稍后重试',
							type: 2
						})
					}).finally(() => {
						this.$ShowLoading({
							show: false
						})
					})
				}
			},
			//查询通知列表
			getNoticeLists() {
				this.$http.get({
					url: '/api/notify/queryPushNotifyUserPageList',
					data: {
						userId: this.user.userId,
						pageNo: this.tabData[this.tabCur].pageNo,
						pageSize: 10
					},
				}).then(data => {
					console.log(data, '通知');
					if (data.success && data.result && data.result.total) {
						if (data.result.current == 1) {
							this.noticeLists = data.result.records
						} else {
							this.noticeLists.push(...data.result.records)
						}
						this.tabData[this.tabCur].isEnd = data.result.current >= data.result.pages
						this.tabData[this.tabCur].pageNo = data.result.current + 1
					}
				}).catch((err) => {
					console.log(err);
				})
			},
			//消息列表滚动
			messageScroll(nowIndex) {
				//查找指定位置以后的未读消息索引
				let index = this.messageLists.findIndex((msg, index) => index >= nowIndex && msg.unreadCount > 0);
				if (index > -1) {
					if (index != 0 && index == this.currentIndex) {
						//已经滚动到列表最底部时，再次双击跳转到顶部
						this.currentIndex = 0
					} else {
						//跳转到未读位置
						this.currentIndex = index
					}
					this.nextView = 'msg-' + this.currentIndex
					this.$nextTick(() => { //释放nextView
						this.nextView = ''
					})
				} else {
					//没有未读消息时跳转到顶部
					this.currentIndex = 0
					this.nextView = 'msg-' + this.currentIndex
					this.$nextTick(() => { //释放nextView
						this.nextView = ''
					})
				}
			},
			//置顶会话
			pinConversation(id, type) {
				let isPinned = !type
				if (this.imReady) {
					imMsg.pinConversation(id, isPinned).then((imResponse) => {
						console.log(imResponse.data);
						uni.showToast({
							title: isPinned ? '置顶成功' : '取消置顶成功',
							icon: 'success'
						})
					}).catch((imError) => {
						console.log(imError);
						uni.showToast({
							title: '操作失败，请重试',
							icon: 'none'
						})
					})
				} else {
					uni.showToast({
						title: '您的聊天账号已离线',
						icon: 'none'
					})
				}
			},
			//删除会话
			delConversation(id) {
				if (this.imReady) {
					imMsg.deleteConversation(id).then((imResponse) => {
						console.log(imResponse.data);
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
					}).catch((imError) => {
						console.log(imError);
						uni.showToast({
							title: '操作失败，请重试',
							icon: 'none'
						})
					})
				} else {
					uni.showToast({
						title: '您的聊天账号已离线',
						icon: 'none'
					})
				}
			},
			//进入对话界面
			goChatBox(id) {
				console.log(id,'id')
				if (this.imReady) {
					let params = {
						cid: id
					}
					this.$goByName('chatbox', params)
				} else {
					this.$ShowToast({
						text: '您的聊天账号已离线，请刷新网页',
						type: 2,
						time: 3
					})
				}
			},
			//通知详情
			goNoticeDetail(e) {
				let json = JSON.parse(e.forwardAddress)
				console.log(json, e, "====")
				if (e.source == 'luckyzz') {
					this.$goByName('luckywheel')
				} else { //activity
					if (json.type == 'expert') {
						this.$CHS.goExpertHome(json.resources)
					} else if (json.type == 'article') {
						if (json.sourceType == 99) {
							this.$CHS.goArticleDetail(json.resources, {
								type: 'user'
							})
						} else {
							this.$CHS.goArticleDetail(json.resources, {
								type: 'expert'
							})
						}
					} else if (json.type == 'information') {
						if (json.sourceType == 2) {
							this.$CHS.goShareDetail(json.resources)
						} else {
							this.$CHS.goDiscussDetail(json.resources)
						}
					} else if (json.type == 'payCard' || json.type == 'payNumCard') {
						this.$goByName('orderlist', {
							tab: 1
						})
					} else if (json.type == 'match') {
						let match = {
							matchId: json.resources,
							sportId: json.sourceType
						}
						this.$CHS.goMatchDetail(match)
					} else if (json.type === 'imApply') {
						this.getExpertMessage(json.resources)
						this.resources=json.resources
					}
				}
				if (!e.isRead && e.targetType != 'ALL') {
					e.isRead = 1
					this.setNoticeRead(e.id, e.source)
				}
			},
			//通知已读
			setNoticeRead(notifyId, source) {
				this.$http.post({
					url: '/api/notify/updateNotifyById',
					noLoading: true,
					data: {
						userId: this.user.userId,
						source,
						notifyId,
					},
				}).then(data => {
					console.log(data);
				}).catch((err) => {
					console.log(err);
				})
			},
			//解析表情信息
			parseTextMsg(messsage) {
				return parseText(messsage)
			},
			//双击顶部
			dbClick() {
				if (this.doublueClick) { // 500ms 内再次点击
					//回到顶部
					this.nextView = 'message'
					this.$nextTick(() => {
						this.nextView = ''
					})
				}
				this.doublueClick = true
				setTimeout(() => {
					this.doublueClick = false // 500ms 内没有第二次点击，就当作单击
				}, 500)
			},
			//选项卡切换
			tabChange(index) {
				this.tabCur = index;
			},
			//触摸滑动开始
			touchStart(e) {
				if (e.changedTouches.length == 1) {
					this.startX = e.changedTouches[0].clientX
					this.startY = e.changedTouches[0].clientY
				}
			},
			//触摸滑动结束
			touchEnd(e) {
				if (e.changedTouches.length == 1) {
					var endX = e.changedTouches[0].clientX;
					var endY = e.changedTouches[0].clientY;
					var xTowards = endX - this.startX;
					var yTowards = endY - this.startY;
					if (xTowards > 50 && Math.abs(yTowards) < 50) { //向右
						console.log('向右')
						if (this.tabCur > 0) {
							this.tabChange(this.tabCur - 1)
						}
					}
					if (xTowards < -50 && Math.abs(yTowards) < 50) { //向左
						console.log('向左')
						let maxlen = this.tabList.length - 1;
						if (this.tabCur < maxlen) {
							this.tabChange(this.tabCur + 1)
						}
					}
				}
			},
			//专家申请消息
			getExpertMessage(resources) {
				this.$http.get({
					url: "/api/im/apply/details",
					data: {
						id: resources
					}
				}).then((data) => {
					if (data.success) {
						console.log(data,'好友数据')
						this.FriendDetail=data.result
						//好友弹窗显示
						this.showPopup=true
					}
				}).catch((err) => {
					console.log(err)
				})
			},
			//修改弹窗的显示隐藏
			getShow(value){
				this.showPopup=value
			}
		}
	}
</script>

<style lang="scss">
	.container {
		padding: 0;

		.scroll-Y {
			height: calc(var(--safe-height) - #{$tabbar-height} - #{$navbar-height});

			/deep/ .uni-scroll-view-content {
				padding-top: 10rpx;
				height: calc(100% - 10rpx);
			}
		}
	}

	.ch-nav {
		.tab-nav {
			width: 100%;

			.tab {
				padding: 0 37rpx;
				font-size: 36rpx;
			}

			.active {
				font-weight: 500;
				color: #333333;
			}
		}
	}

	.body {
		min-height: 100%;
		box-sizing: border-box;
		padding: 10rpx 0 20rpx;

		//min-height: calc(100vh - 96rpx - 140rpx - var(--safe-area-inset-bottom));
		.message {
			.message-list {
				background: #FFFFFF;

				.slot-button {
					width: 320rpx;
					height: 100%;

					.slot-button-text {
						height: 100%;
						width: 50%;
					}

					.pinned-msg {
						background: #4D88FF;

						&.grey {
							background: #a6a6a6;
						}
					}

					.delete-msg {
						background: #FF6674;
					}
				}

				.swipe-item:last-child {
					.message-item {
						.right {
							border-bottom: none;
						}
					}
				}

				.message-item {
					align-items: center;
					padding: 0 0 0 20rpx;
					-webkit-touch-callout: none;
					-webkit-user-select: none;
					-khtml-user-select: none;
					user-select: none;

					&.isPinned {
						background-color: #EDEDED;
					}

					.left {
						align-items: center;
						position: relative;
						padding: 24rpx 0;
						box-sizing: border-box;

						.avatar {
							width: 96rpx;
							height: 96rpx;
							border-radius: 50%;

							&.bg {
								background-color: #FFFFFF;
								background-repeat: no-repeat;
								background-size: 100%;
							}
						}

						.note {
							display: flex;
							align-items: center;
							justify-content: center;
							position: absolute;
							top: 14rpx;
							right: -8rpx;
							background: $uni-primary;
							border-radius: 20rpx;
							padding: 10rpx 14rpx;

							text {
								font-size: 26rpx;
								line-height: 22rpx;
								font-family: Arial;
								color: #FFFFFF;
							}
						}
					}

					.right {
						flex: 2;
						height: 144rpx;
						padding: 0 20rpx;
						border-bottom: 1rpx solid #EDEDED;
						align-items: center;

						.content {
							width: 564rpx;

							.top {
								align-items: center;
								justify-content: space-between;
								margin-bottom: 18rpx;

								.title {
									font-size: 32rpx;
									line-height: 32rpx;
									font-weight: 500;
									color: #333333;
								}

								.time {
									font-size: 24rpx;
									line-height: 24rpx;
									font-family: Arial;
									color: #B3B3B3;
								}
							}

							.info {
								font-size: 26rpx;
								line-height: 1.2;
								color: #999999;
								width: 564rpx;
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;

								.face-message {
									margin: 0 5rpx;
									width: 26rpx;
									height: 26rpx;
									vertical-align: bottom;
								}
							}
						}
					}
				}
			}
		}

		.notice {
			padding: 0 20rpx;

			.notice-list {
				.notice-item {
					background: #FFFFFF;
					border-radius: 10rpx;
					padding: 0 20rpx 30rpx;
					margin-bottom: 20rpx;

					.notice-head {
						align-items: center;
						line-height: 1;
						padding: 20rpx 0;

						//box-shadow: 0rpx 1rpx 0rpx 0rpx #EDEDED;
						image {
							width: 40rpx;
							height: 40rpx;
						}

						.text-bold {
							flex: 2;
							margin-left: 20rpx;
							font-size: 30rpx;
							font-weight: bold;
						}

						.date {
							font-size: 22rpx;
							color: #B3B3B3;
						}
					}

					.notice-title {
						margin-top: 20rpx;
						font-size: 26rpx;
						font-weight: 500;
						line-height: 1;
					}

					.notice-content {
						margin-top: 18rpx;
						font-size: 24rpx;
						color: #666666;
						line-height: 36rpx;
					}

					&.read {

						.text-bold,
						.notice-title,
						.notice-content {
							color: #999999;
						}
					}
				}
			}

			.list-end {
				align-items: center;

				text {
					font-size: 24rpx;
					color: #B3B3B3;
					line-height: 36rpx;
					margin: 0 20rpx;
				}

				.list-end-line {
					width: 30rpx;
					height: 1rpx;
					background: #CCCCCC;
				}
			}
		}
	}
</style>